package dao;

import model.Category;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DataSourceUtils;

import java.sql.SQLException;
import java.util.List;

public class CategoryDao {
    public List<Category> GetAllType() throws SQLException {
        QueryRunner r=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from category";
//        try {
//            Connection conn = DataSourceUtils.getDataSource().getConnection();
//            System.out.println("conn对象：" + conn);
//            System.out.println("当前连接到的数据库是：" + conn.getCatalog());
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("获取数据库连接时发生异常！");
//        }
        return r.query(sql,new BeanListHandler<Category>(Category.class));
    }
    public Category selectTypeNameByID(int category_id) throws SQLException {
        QueryRunner r=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from category where id=?";
        return r.query(sql,new BeanHandler<Category>(Category.class),category_id);
    }
    public Category select(int id) throws SQLException {
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from category where id = ?";
        return r.query(sql, new BeanHandler<Category>(Category.class),id);
    }
    public void insert(Category c) throws SQLException {
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "insert into category(name,is_use) values(?,?)";
        r.update(sql,c.getName(),c.isIs_use());
    }
    public void update(Category t) throws SQLException {
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "update category set name=? ,is_use=? where id = ?";
        r.update(sql,t.getName(),t.isIs_use(),t.getId());
    }
    public void delete(int id) throws SQLException {
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "delete from category where id = ?";
        r.update(sql,id);
    }
}
